package com.heima.article.listen;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.HotArticleService;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UpdateHotArticleJob {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    HotArticleService hotArticleService;

    @XxlJob("updateHotArticleJob")
    public ReturnT updateHotArticleHandler(String params) {
        // 1 获取redis中 最近10秒钟产生 最新的行为数据
        List<NewBehaviorDTO> behaviorList = getRedisBehaviorList();
        if (CollectionUtils.isEmpty(behaviorList)) {
            log.info("热文章分值更新: 太冷清了 未产生任何文章行为 调度任务完成....");
            return ReturnT.SUCCESS;
        }
        // 2 根据新的行为为数据进行聚合处理,每篇文章 封装成一条数据
        List<AggBehaviorDTO> aggBehaviorList = getAggBehaviorList(behaviorList);

        // 3 根据行为聚合数据 修改文章的热度值
        aggBehaviorList.forEach(hotArticleService::updateApArticle);
        return ReturnT.SUCCESS;
    }

    /**
     * 按照文章分组并统计每篇文章的聚合统计
     * <p>
     * NewBehaviorDTO->AggBehaviorDTO
     *
     * @param behaviorList
     * @return
     */
    private List<AggBehaviorDTO> getAggBehaviorList(List<NewBehaviorDTO> behaviorList) {
        // 按照文章id进行分组

        List<AggBehaviorDTO> aggBehaviorDTOList = new ArrayList<>();

        Map<Long, List<NewBehaviorDTO>> behaviorGroupByArticleId = behaviorList.stream()
                .collect(Collectors.groupingBy(NewBehaviorDTO::getArticleId));

        // 计算每个分组的聚合数据
        behaviorGroupByArticleId.forEach((articleId, behaviorDTOList) -> {
            // 将每一个behaviorList集合封装成一个对象  AggBehavior
            // {add:1,articleId:11 ,type:VIEWS} {add:1,articleId:11 ,type:LIKES}
            Optional<AggBehaviorDTO> reduceRsult = behaviorDTOList.stream().map(behavior -> {
                AggBehaviorDTO aggBehaviorDTO = new AggBehaviorDTO();
                aggBehaviorDTO.setArticleId(articleId);
                switch (behavior.getType()) {
                    case LIKES:
                        aggBehaviorDTO.setLike(behavior.getAdd());
                        break;
                    case VIEWS:
                        aggBehaviorDTO.setView(behavior.getAdd());
                        break;
                    case COLLECTION:
                        aggBehaviorDTO.setCollect(behavior.getAdd());
                        break;
                    case COMMENT:
                        aggBehaviorDTO.setComment(behavior.getAdd());
                        break;
                    default:
                }
                return aggBehaviorDTO;
            }).reduce((agg1, agg2) -> {
                agg1.setLike(agg1.getLike() + agg2.getLike());
                agg1.setView(agg1.getView() + agg2.getView());
                agg1.setCollect(agg1.getCollect() + agg2.getCollect());
                agg1.setComment(agg1.getComment() + agg2.getComment());
                return agg1;
            });
            // 判断是否包含聚合结果
            if (reduceRsult.isPresent()) {
                aggBehaviorDTOList.add(reduceRsult.get());
            }
        });
        return aggBehaviorDTOList;
    }

    /**
     * 获取最新的行为集合
     *
     * @return
     */
    private List<NewBehaviorDTO> getRedisBehaviorList() {
        // 1.1 获取redis list中数据的长度
        Long size = redisTemplate.opsForList()
                .size(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST);
        List<Object> pipelinedResult = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                // 开启redis的管道命令
                connection.openPipeline();
                // 1.2 通过lrage方法(0,size-1) 获取redis列表数据
                connection.lRange(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST.getBytes(),
                        0, size - 1);
                // 1.3 通过ltrim方法(size,-1) 获取redis列表数据
                connection.lTrim(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST.getBytes(),
                        size, -1);
                return null;
            }
        }, RedisSerializer.string());
        // 统一获取管道命令 结果 list
        if (CollectionUtils.isEmpty(pipelinedResult)) {
            List<String> list = (List<String>) pipelinedResult.get(0);
            return list.stream().map(str -> JSON.parseObject(str, NewBehaviorDTO.class))
                    .collect(Collectors.toList());
        }
        return null;
    }
}